// index.js
// 研发创新效果分析看板核心交互与图表渲染脚本
// 主要功能：模态框穿透、图表渲染入口、静态数据结构示例
// 所有内容均有中文注释，便于理解和维护

// =====================
// 1. 图表实例管理（避免重复创建）
// =====================
const chartInstances = {};

// 销毁指定canvas的Chart实例
function destroyChart(canvasId) {
    if (chartInstances[canvasId]) {
        chartInstances[canvasId].destroy();
        delete chartInstances[canvasId];
    }
}

// 创建Chart实例并保存引用
function createChart(canvasId, config) {
    // 先销毁已存在的实例
    destroyChart(canvasId);
    // 创建新实例并保存
    chartInstances[canvasId] = new Chart(document.getElementById(canvasId), config);
    return chartInstances[canvasId];
}

// =====================
// 2. 模态框穿透查询逻辑
// =====================
const modal = document.getElementById('detailModal');
const modalTitle = document.getElementById('modalTitle');
const modalContent = document.getElementById('modalContent');
const closeModal = document.getElementById('closeModal');
const closeModalBtn = document.getElementById('closeModalBtn');

// 打开模态框，type为指标标识
window.showDetail = function (type) {
    modal.classList.remove('hidden');
    // 根据type填充不同内容
    renderModalContent(type);
};

closeModal.onclick = closeModalBtn.onclick = function () {
    modal.classList.add('hidden');
};

// =====================
// 3. 模态内容渲染（全覆盖）
// =====================
function renderModalContent(type) {
    let title = '';
    let html = '';
    switch (type) {
        // 核心指标穿透查询
        case 'rdFee':
            title = '研发费用总数 - 趋势分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>指标解读</b><br>
                    研发费用总数反映了企业在研发创新方面的投入规模，是衡量企业创新能力的重要指标。同比和环比增长表明企业在研发投入方面的持续性和增长趋势。
                </div>
                <div class="flex flex-col md:flex-row gap-4 items-stretch">
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">年度趋势</h4>
                        <canvas id="modalRdFeeChart" height="120"></canvas>
                    </div>
                    <div class="flex-1 bg-light rounded-lg p-3 flex flex-col items-center justify-center">
                        <h4 class="text-md font-medium mb-2">费用来源分布</h4>
                        <canvas id="modalRdFeeSourceChart" height="120"></canvas>
                    </div>
                </div>
            `;
            setTimeout(() => {
                // 年度趋势折线图
                createChart('modalRdFeeChart', {
                    type: 'line',
                    data: {
                        labels: ['2019', '2020', '2021', '2022', '2023'],
                        datasets: [{
                            label: '研发费用(万元)',
                            data: [8800, 9200, 9500, 9800, 10000],
                            borderColor: '#165DFF',
                            backgroundColor: 'rgba(22,93,255,0.1)',
                            fill: true,
                            tension: 0.4
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { display: true } },
                        scales: {
                            x: { grid: { display: false }, ticks: { color: '#86909C' } },
                            y: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { color: '#86909C' } }
                        }
                    }
                });
                // 费用来源饼图
                createChart('modalRdFeeSourceChart', {
                    type: 'doughnut',
                    data: {
                        labels: ['政府资助', '企业自筹', '合作研发', '其他来源'],
                        datasets: [{
                            data: [35, 45, 15, 5],
                            backgroundColor: ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F'],
                            borderWidth: 0
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } }
                    }
                });
            }, 100);
            break;
        case 'rdPersonnel':
            title = '研发人员数 - 趋势分析';
            html = `<canvas id="modalRdPersonnelChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalRdPersonnelChart', '研发人员数', [750, 820, 880, 930, 980, 1050, 1120, 1160, 1200], ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023']), 100);
            break;
        case 'innovationReturn':
            title = '创新回报率 - 趋势分析';
            html = `<canvas id="modalInnovationReturnChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalInnovationReturnChart', '创新回报率', [18, 20, 22, 23, 24, 25, 26, 28, 30], ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023']), 100);
            break;
        case 'patentConversion':
            title = '专利转化率 - 趋势分析';
            html = `<canvas id="modalPatentConversionChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalPatentConversionChart', '专利转化率', [2.5, 2.8, 3.0, 3.2, 3.5, 4.0, 4.2, 4.5, 5.0], ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023']), 100);
            break;
        case 'rdInvestmentRatio':
            title = '研发投入比 - 趋势分析';
            html = `<canvas id="modalRdInvestmentRatioChart" height="300"></canvas>`;
            setTimeout(() => renderLineChart('modalRdInvestmentRatioChart', '研发投入比', [22, 23, 24, 25, 26, 27, 28, 29, 30], ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023']), 100);
            break;

        // 趋势分析穿透查询
        case 'rdTrendAnalysis':
            title = '研发创新投入与产出趋势 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>分析说明</b><br>
                    该图表展示了研发费用总额（柱状图）与研发投入比、创新回报率、专利转化率（折线图）的对比趋势，反映了投入与产出的关系。
                </div>
                <canvas id="modalRdTrendAnalysisChart" height="300"></canvas>
            `;
            setTimeout(() => {
                const years = ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023'];
                createChart('modalRdTrendAnalysisChart', {
                    type: 'bar',
                    data: {
                        labels: years,
                        datasets: [
                            {
                                label: '研发费用总额(万元)',
                                data: [6500, 7200, 7800, 8200, 8800, 9200, 9500, 9800, 10000],
                                backgroundColor: '#165DFF',
                                yAxisID: 'y',
                                barThickness: 20, // 模态框中柱状图宽度稍小
                                maxBarThickness: 25
                            },
                            {
                                label: '研发投入比(%)',
                                data: [22, 23, 24, 25, 26, 27, 28, 29, 30],
                                borderColor: '#0FC6C2',
                                backgroundColor: 'rgba(15,198,194,0.1)',
                                type: 'line',
                                yAxisID: 'y1'
                            },
                            {
                                label: '创新回报率(%)',
                                data: [18, 20, 22, 23, 24, 25, 26, 28, 30],
                                borderColor: '#FF7D00',
                                backgroundColor: 'rgba(255,125,0,0.1)',
                                type: 'line',
                                yAxisID: 'y1'
                            },
                            {
                                label: '专利转化率(%)',
                                data: [2.5, 2.8, 3.0, 3.2, 3.5, 4.0, 4.2, 4.5, 5.0],
                                borderColor: '#F53F3F',
                                backgroundColor: 'rgba(245,63,63,0.1)',
                                type: 'line',
                                yAxisID: 'y1'
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: { position: 'bottom' },
                            tooltip: {
                                mode: 'index',
                                intersect: false
                            }
                        },
                        scales: {
                            x: { grid: { display: false } },
                            y: {
                                type: 'linear',
                                display: true,
                                position: 'left',
                                title: { display: true, text: '研发费用(万元)' }
                            },
                            y1: {
                                type: 'linear',
                                display: true,
                                position: 'right',
                                title: { display: true, text: '比率(%)' },
                                grid: { drawOnChartArea: false }
                            }
                        }
                    }
                });
            }, 100);
            break;

        // 结构分析穿透查询
        case 'rdFeeStructure':
            title = '研发费用按投入结构分类 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>分析说明</b><br>
                    展示了研发费用在不同投入结构分类中的分布情况，包括人员费用、设备费用、材料费用、外包费用等。
                </div>
                <canvas id="modalRdFeeStructureChart" height="300"></canvas>
            `;
            setTimeout(() => renderPieChart('modalRdFeeStructureChart', ['结构分类1', '结构分类2', '结构分类3', '结构分类4', '结构分类5'], [45, 25, 15, 10, 5]), 100);
            break;
        case 'rdPersonnelStructure':
            title = '研发人数按投入结构分类 - 详细分析';
            html = `<canvas id="modalRdPersonnelStructureChart" height="300"></canvas>`;
            setTimeout(() => renderPieChart('modalRdPersonnelStructureChart', ['结构分类1', '结构分类2', '结构分类3', '结构分类4', '结构分类5'], [30, 35, 25, 8, 2]), 100);
            break;
        case 'rdFeeField':
            title = '研发费用按投入领域分类 - 详细分析';
            html = `<canvas id="modalRdFeeFieldChart" height="300"></canvas>`;
            setTimeout(() => renderPieChart('modalRdFeeFieldChart', ['领域1', '领域2', '领域3', '领域4', '领域5'], [35, 25, 20, 15, 5]), 100);
            break;
        case 'rdPersonnelField':
            title = '研发人数按投入领域分类 - 详细分析';
            html = `<canvas id="modalRdPersonnelFieldChart" height="300"></canvas>`;
            setTimeout(() => renderPieChart('modalRdPersonnelFieldChart', ['领域1', '领域2', '领域3', '领域4', '领域5'], [40, 25, 18, 12, 5]), 100);
            break;

        // 主要成果明细穿透查询
        case 'costSavingTop5':
            title = '项目成本TOP5 - 详细分析';
            html = `
                <div class="mb-3 p-3 bg-light rounded text-sm text-gray-700">
                    <b>分析说明</b><br>
                    展示了研发项目中成本节约效果最好的前5个项目，反映了研发创新的经济效益。
                </div>
                <canvas id="modalCostSavingChart" height="300"></canvas>
            `;
            setTimeout(() => renderHorizontalBarChart('modalCostSavingChart', ['项目A', '项目B', '项目C', '项目D', '项目E'], [850, 720, 680, 550, 480], '成本节约(万元)'), 100);
            break;
        case 'innovationReturnTop5':
            title = '创新回报率TOP5 - 详细分析';
            html = `<canvas id="modalInnovationReturnTop5Chart" height="300"></canvas>`;
            setTimeout(() => renderHorizontalBarChart('modalInnovationReturnTop5Chart', ['项目A', '项目B', '项目C', '项目D', '项目E'], [45, 38, 32, 28, 25], '创新回报率(%)'), 100);
            break;
        case 'contractAmountTop5':
            title = '合同额TOP5 - 详细分析';
            html = `<canvas id="modalContractAmountChart" height="300"></canvas>`;
            setTimeout(() => renderHorizontalBarChart('modalContractAmountChart', ['项目A', '项目B', '项目C', '项目D', '项目E'], [1200, 980, 850, 720, 650], '合同额(万元)'), 100);
            break;
        case 'patentTop5':
            title = '专利数TOP5 - 详细分析';
            html = `<canvas id="modalPatentTop5Chart" height="300"></canvas>`;
            setTimeout(() => renderHorizontalBarChart('modalPatentTop5Chart', ['项目A', '项目B', '项目C', '项目D', '项目E'], [25, 22, 18, 15, 12], '专利数(件)'), 100);
            break;
        default:
            title = '详细分析';
            html = '<div>暂无详细内容</div>';
    }
    modalTitle.innerText = title;
    modalContent.innerHTML = html;
}

// =====================
// 4. 图表渲染函数
// =====================
// 折线图
function renderLineChart(canvasId, label, data, labels) {
    createChart(canvasId, {
        type: 'line',
        data: {
            labels: labels || ['一月', '二月', '三月', '四月', '五月'],
            datasets: [{
                label: label,
                data: data,
                borderColor: '#165DFF',
                backgroundColor: 'rgba(22,93,255,0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: true } },
            scales: {
                x: { grid: { display: false }, ticks: { color: '#86909C' } },
                y: { grid: { color: 'rgba(0,0,0,0.05)' }, ticks: { color: '#86909C' } }
            }
        }
    });
}

// 饼图
function renderPieChart(canvasId, labels, data) {
    const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'];
    createChart(canvasId, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: data,
                backgroundColor: colors,
                borderWidth: 0,
                hoverOffset: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            cutout: '70%',
            plugins: {
                legend: { position: 'bottom' },
                tooltip: {
                    callbacks: {
                        label: function (context) {
                            const percentage = context.parsed;
                            const numericValue = Math.round(10000 * percentage / 100);
                            return `${context.label}: ${percentage}% (${numericValue}万元)`;
                        }
                    }
                }
            }
        }
    });
}

// 水平条形图
function renderHorizontalBarChart(canvasId, labels, data, label) {
    const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'];
    createChart(canvasId, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: label,
                data: data,
                backgroundColor: colors,
                borderWidth: 0,
                borderRadius: 4
            }]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: 'rgba(255, 255, 255, 0.9)',
                    titleColor: '#1D2129',
                    bodyColor: '#4E5969',
                    borderColor: 'rgba(22, 93, 255, 0.2)',
                    borderWidth: 1,
                    padding: 12,
                    boxPadding: 6,
                    usePointStyle: true
                }
            },
            scales: {
                x: {
                    grid: { color: 'rgba(0, 0, 0, 0.05)' },
                    ticks: { color: '#86909C', font: { size: 12 } },
                    title: { display: true, text: label, color: '#86909C', font: { size: 12 } }
                },
                y: {
                    grid: { display: false },
                    ticks: { color: '#86909C', font: { size: 11 } }
                }
            }
        }
    });
}

// 生成图例HTML
function generateLegend(containerId, labels, data, colors, totalValue = null) {
    const legendContainer = document.getElementById(containerId);
    if (!legendContainer) return;

    let legendHTML = '';
    labels.forEach((label, index) => {
        const percentage = data[index];
        const color = colors[index];
        // 计算数字值（如果有总数的话）
        const numericValue = totalValue ? Math.round(totalValue * percentage / 100) : null;

        legendHTML += `
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-2">
                    <div class="w-3 h-3 rounded-full" style="background-color: ${color}"></div>
                    <span class="text-sm text-gray-700">${label}</span>
                </div>
                <span class="text-sm font-medium text-gray-900">
                    ${percentage}%${numericValue ? ` (${numericValue})` : ''}
                </span>
            </div>
        `;
    });
    legendContainer.innerHTML = legendHTML;
}

// =====================
// 5. 页面加载后自动渲染图表
// =====================
window.onload = function () {
    // 清理所有现有的Chart实例，避免重复创建
    Object.keys(chartInstances).forEach(canvasId => {
        destroyChart(canvasId);
    });

    // 侧边栏切换功能
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');
    const toggleSidebar = document.getElementById('toggleSidebar');
    if (sidebar && mainContent && toggleSidebar) {
        toggleSidebar.onclick = function () {
            sidebar.classList.toggle('w-64');
            sidebar.classList.toggle('w-16');
            mainContent.classList.toggle('pl-64');
            mainContent.classList.toggle('pl-16');
            sidebar.classList.toggle('sidebar-collapsed');
        };
    }

    // 研发创新投入与产出趋势图表（组合图）
    if (document.getElementById('rdTrendChart')) {
        const years = ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023'];
        createChart('rdTrendChart', {
            type: 'bar',
            data: {
                labels: years,
                datasets: [
                    {
                        label: '研发费用总额(万元)',
                        data: [6500, 7200, 7800, 8200, 8800, 9200, 9500, 9800, 10000],
                        backgroundColor: '#165DFF',
                        yAxisID: 'y',
                        barThickness: 25, // 设置柱状图宽度
                        maxBarThickness: 30 // 最大宽度限制
                    },
                    {
                        label: '研发投入比(%)',
                        data: [22, 23, 24, 25, 26, 27, 28, 29, 30],
                        borderColor: '#0FC6C2',
                        backgroundColor: 'rgba(15,198,194,0.1)',
                        type: 'line',
                        yAxisID: 'y1'
                    },
                    {
                        label: '创新回报率(%)',
                        data: [18, 20, 22, 23, 24, 25, 26, 28, 30],
                        borderColor: '#FF7D00',
                        backgroundColor: 'rgba(255,125,0,0.1)',
                        type: 'line',
                        yAxisID: 'y1'
                    },
                    {
                        label: '专利转化率(%)',
                        data: [2.5, 2.8, 3.0, 3.2, 3.5, 4.0, 4.2, 4.5, 5.0],
                        borderColor: '#F53F3F',
                        backgroundColor: 'rgba(245,63,63,0.1)',
                        type: 'line',
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { boxWidth: 12, padding: 15, color: '#4E5969', font: { size: 12 } }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { color: '#86909C', font: { size: 12 } }
                    },
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: { display: true, text: '研发费用(万元)', color: '#86909C', font: { size: 12 } },
                        grid: { color: 'rgba(0, 0, 0, 0.05)' },
                        ticks: { color: '#86909C' }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        title: { display: true, text: '比率(%)', color: '#86909C', font: { size: 12 } },
                        grid: { drawOnChartArea: false },
                        ticks: { color: '#86909C' }
                    }
                }
            }
        });
    }

    // 结构分析饼图
    // 研发费用按投入结构分类
    if (document.getElementById('rdFeeStructureChart')) {
        const labels = ['结构分类1', '结构分类2', '结构分类3', '结构分类4', '结构分类5'];
        const data = [45, 25, 15, 10, 5];
        const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'];

        createChart('rdFeeStructureChart', {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: colors,
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                const percentage = context.parsed;
                                const numericValue = Math.round(10000 * percentage / 100);
                                return `${context.label}: ${percentage}% (${numericValue}万元)`;
                            }
                        }
                    }
                }
            }
        });

        generateLegend('rdFeeStructureLegend', labels, data, colors, 10000); // 研发费用总数10000万元
    }

    // 研发人数按投入结构分类
    if (document.getElementById('rdPersonnelStructureChart')) {
        const labels = ['结构分类1', '结构分类2', '结构分类3', '结构分类4', '结构分类5'];
        const data = [30, 35, 25, 8, 2];
        const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'];

        createChart('rdPersonnelStructureChart', {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: colors,
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                const percentage = context.parsed;
                                const numericValue = Math.round(1200 * percentage / 100);
                                return `${context.label}: ${percentage}% (${numericValue}人)`;
                            }
                        }
                    }
                }
            }
        });

        generateLegend('rdPersonnelStructureLegend', labels, data, colors, 1200); // 研发人员总数1200人
    }

    // 研发费用按投入领域分类
    if (document.getElementById('rdFeeFieldChart')) {
        const labels = ['领域1', '领域2', '领域3', '领域4', '领域5'];
        const data = [35, 25, 20, 15, 5];
        const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'];

        createChart('rdFeeFieldChart', {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: colors,
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                const percentage = context.parsed;
                                const numericValue = Math.round(10000 * percentage / 100);
                                return `${context.label}: ${percentage}% (${numericValue}万元)`;
                            }
                        }
                    }
                }
            }
        });

        generateLegend('rdFeeFieldLegend', labels, data, colors, 10000); // 研发费用总数10000万元
    }

    // 研发人数按投入领域分类
    if (document.getElementById('rdPersonnelFieldChart')) {
        const labels = ['领域1', '领域2', '领域3', '领域4', '领域5'];
        const data = [40, 25, 18, 12, 5];
        const colors = ['#165DFF', '#0FC6C2', '#FF7D00', '#F53F3F', '#86909C'];

        createChart('rdPersonnelFieldChart', {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: colors,
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(255, 255, 255, 0.9)',
                        titleColor: '#1D2129',
                        bodyColor: '#4E5969',
                        borderColor: 'rgba(22, 93, 255, 0.2)',
                        borderWidth: 1,
                        padding: 12,
                        boxPadding: 6,
                        usePointStyle: true,
                        callbacks: {
                            label: function (context) {
                                const percentage = context.parsed;
                                const numericValue = Math.round(1200 * percentage / 100);
                                return `${context.label}: ${percentage}% (${numericValue}人)`;
                            }
                        }
                    }
                }
            }
        });

        generateLegend('rdPersonnelFieldLegend', labels, data, colors, 1200); // 研发人员总数1200人
    }

    // 主要成果明细图表
    // 成本节约TOP5
    if (document.getElementById('costSavingChart')) {
        renderHorizontalBarChart('costSavingChart', ['项目A', '项目B', '项目C', '项目D', '项目E'], [850, 720, 680, 550, 480], '成本节约(万元)');
    }

    // 创新回报TOP5
    if (document.getElementById('innovationReturnChart')) {
        renderHorizontalBarChart('innovationReturnChart', ['项目A', '项目B', '项目C', '项目D', '项目E'], [45, 38, 32, 28, 25], '创新回报率(%)');
    }

    // 合同额TOP5
    if (document.getElementById('contractAmountChart')) {
        renderHorizontalBarChart('contractAmountChart', ['项目A', '项目B', '项目C', '项目D', '项目E'], [1200, 980, 850, 720, 650], '合同额(万元)');
    }

    // 专利数TOP5
    if (document.getElementById('patentChart')) {
        renderHorizontalBarChart('patentChart', ['项目A', '项目B', '项目C', '项目D', '项目E'], [25, 22, 18, 15, 12], '专利数(件)');
    }
}; 